package com.like.banzipao.server.util.roomstate.playroomstate

import com.like.banzipao.server.model.FriendType
import com.like.banzipao.server.model.Player
import com.like.banzipao.server.model.PlayerState
import com.like.banzipao.server.model.Poker
import com.like.banzipao.server.model.PokerState
import com.like.banzipao.server.model.Room
import com.like.banzipao.server.util.roomstate.BaoType

/**
 * 爆与反爆 1 vs 1 对决模式
 */
class OneVsOneRoomState(room: Room, private val baoType: BaoType, private val onWin: () -> Unit) : PlayRoomState(room) {
    override fun onPlayPlayed(player: Player, nextPlayer: Player, curPlayedPokers: List<Poker>): Boolean {
        player.state = PlayerState.PLAY_PLAYED
        curPlayedPokers.forEach {
            it.state = PokerState.PLAY_PLAYED
        }
        if (!checkWin(player, nextPlayer)) {
            player.nextValidPlayerTurn(PlayerState.PLAY_TURN)
            prePlayedPokers.clear()
            prePlayedPokers.addAll(curPlayedPokers)
        } else {
            onWin()
        }
        return true
    }

    override fun onPlayPass(player: Player, nextPlayer: Player) {
        player.state = PlayerState.PLAY_PASS
        player.nextValidPlayerTurn(PlayerState.PLAY_TURN_WIN)
    }

    override fun getDealerUserId(): Int {
        return room.players.find {
            it?.friendTypeTemp == FriendType.BAO
        }?.user?.id ?: -1
    }

    override fun getIntegralChange(player: Player): Int {
        return if (player.state == PlayerState.PLAY_WIN) {
            if (baoType == BaoType.FAN_BAO) 24 else 18
        } else {
            if (baoType == BaoType.FAN_BAO) -24 else -18
        }
    }

    private fun checkWin(player: Player, nextPlayer: Player): Boolean {
        // 任意一家出完本局就结束了。
        if (player.isAllPokersPlayed()) {
            player.state = PlayerState.PLAY_WIN
            nextPlayer.state = PlayerState.PLAY_LOSE
            if (baoType == BaoType.FAN_BAO) {
                player.integral += 24
                nextPlayer.integral -= 24
            } else if (baoType == BaoType.DRAW_FAN_BAO) {
                player.integral += 18
                nextPlayer.integral -= 18
            }
            return true
        }
        return false
    }

}